/**
 * 研发流程状态机 - 状态转换规则定义
 * 根据研发流程状态机.md文档实现
 */

// 引入状态常量
const {
  PROJECT_STATUS,
  ACTIVE_STATE,
  PROJECT_REVIEW_SUB_STATUS,
  DORMANT_SUB_STATUS,
  STATE_EVENTS,
  ROLES
} = require('./constants');

/**
 * 状态转换规则定义
 * 格式: [当前状态]_[事件] -> { target, activeState, subState, roles, description }
 */
const STATE_TRANSITIONS = {
  // 项目审核状态转移
  [`${PROJECT_STATUS.NONE}_${STATE_EVENTS.SUBMIT_REQUEST}`]: {
    target: PROJECT_STATUS.PROJECT_REVIEW,
    subState: PROJECT_REVIEW_SUB_STATUS.DIRECTOR,
    description: "提交功能需求表",
    roles: [ROLES.BUSINESS_STAFF, ROLES.DIRECTOR]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.DIRECTOR_APPROVE}`]: {
    target: PROJECT_STATUS.PROJECT_REVIEW,
    subState: PROJECT_REVIEW_SUB_STATUS.RD_MANAGER,
    description: "董事长审核通过",
    roles: [ROLES.DIRECTOR]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.DIRECTOR_REJECT}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: DORMANT_SUB_STATUS.ARCHIVE,
    description: "项目立项不通过",
    roles: [ROLES.DIRECTOR]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.MANAGER_APPROVE}`]: {
    target: PROJECT_STATUS.PROJECT_REVIEW,
    subState: PROJECT_REVIEW_SUB_STATUS.ASSIGNMENT,
    description: "研发经理审核通过",
    roles: [ROLES.RESEARCH_MANAGER]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.PROJECT_ASSIGN_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.HARDWARE_CONFIRM,
    description: "提交分配",
    roles: [ROLES.RESEARCH_MANAGER]
  },
  
  // 休眠状态转移
  [`${PROJECT_STATUS.ACTIVE}_${STATE_EVENTS.SLEEP_REQUEST}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: DORMANT_SUB_STATUS.REVIEW,
    description: "业务提交休眠申请",
    roles: [ROLES.BUSINESS_STAFF]
  },
  
  [`${PROJECT_STATUS.DORMANT}_${STATE_EVENTS.SLEEP_APPROVE}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: DORMANT_SUB_STATUS.ARCHIVE,
    description: "休眠审核通过",
    roles: [ROLES.RESEARCH_MANAGER]
  },
  
  [`${PROJECT_STATUS.DORMANT}_${STATE_EVENTS.SLEEP_REJECT}`]: {
    target: PROJECT_STATUS.ACTIVE,
    description: "休眠审核不通过",
    roles: [ROLES.RESEARCH_MANAGER]
  },
  
  [`${PROJECT_STATUS.DORMANT}_${STATE_EVENTS.WAKEUP_REQUEST}`]: {
    target: PROJECT_STATUS.ACTIVE,
    description: "业务提交唤醒申请",
    roles: [ROLES.BUSINESS_STAFF]
  },
  
  // 硬件确认状态转移
  [`${ACTIVE_STATE.HARDWARE_CONFIRM}_${STATE_EVENTS.HW_CONFIRM_COMPLETED}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.HARDWARE,
    description: "硬件确认完成",
    roles: [ROLES.HARDWARE_ENGINEER]
  },
  
  [`${ACTIVE_STATE.HARDWARE_CONFIRM}_${STATE_EVENTS.HW_EXISTING}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.DEBUG,
    description: "已有硬件",
    roles: [ROLES.HARDWARE_ENGINEER]
  },
  
  // 软硬件调试状态转移
  [`${ACTIVE_STATE.DEBUG}_${STATE_EVENTS.DEBUG_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.DATA_SYNC,
    description: "调试完成",
    roles: [ROLES.SOFTWARE_ENGINEER, ROLES.HARDWARE_ENGINEER]
  },
  
  [`${ACTIVE_STATE.DEBUG}_${STATE_EVENTS.HW_CONFIRM_AGAIN}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.HARDWARE_CONFIRM,
    description: "重新确认硬件",
    roles: [ROLES.SOFTWARE_ENGINEER, ROLES.HARDWARE_ENGINEER]
  },
  
  // 资料同步状态转移
  [`${ACTIVE_STATE.DATA_SYNC}_${STATE_EVENTS.DATA_SYNC_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.TESTING,
    description: "资料同步完成",
    roles: [ROLES.SOFTWARE_ENGINEER]
  },
  
  // 测试验证状态转移
  [`${ACTIVE_STATE.TESTING}_${STATE_EVENTS.TEST_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.CUSTOMER_CONFIRM,
    description: "测试完成",
    roles: [ROLES.TEST_ENGINEER]
  },
  
  // 客户确认状态转移
  [`${ACTIVE_STATE.CUSTOMER_CONFIRM}_${STATE_EVENTS.CUSTOMER_APPROVE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.ORDER_PREPARATION,
    description: "客户确认通过",
    roles: [ROLES.BUSINESS_STAFF]
  },
  
  // 订单准备状态转移
  [`${ACTIVE_STATE.ORDER_PREPARATION}_${STATE_EVENTS.ORDER_READY}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.PRODUCTION,
    description: "订单准备完成",
    roles: [ROLES.PRODUCTION_MANAGER]
  },
  
  // 生产状态转移
  [`${ACTIVE_STATE.PRODUCTION}_${STATE_EVENTS.PRODUCTION_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.PRODUCT_FEEDBACK,
    description: "生产完成",
    roles: [ROLES.PRODUCTION_MANAGER]
  },
  
  // 产品反馈状态转移
  [`${ACTIVE_STATE.PRODUCT_FEEDBACK}_${STATE_EVENTS.FEEDBACK_COMPLETE}`]: {
    target: PROJECT_STATUS.COMPLETED,
    description: "产品反馈完成",
    roles: [ROLES.BUSINESS_STAFF]
  }
};

/**
 * 验证状态转换是否合法
 * @param {Object} currentState 当前状态 {level1, level2, level3, level4}
 * @param {String} event 事件代码
 * @param {String} userRole 用户角色
 * @returns {Object} 验证结果 {valid: boolean, reason: string, transition: Object}
 */
function validateTransition(currentState, event, userRole) {
  // 构造转换规则键
  const transitionKey = `${currentState.level1}_${event}`;
  
  // 获取转换规则
  const transition = STATE_TRANSITIONS[transitionKey];
  
  if (!transition) {
    return {
      valid: false,
      reason: '无效的状态转换',
      transition: null
    };
  }
  
  // 检查角色权限
  if (!transition.roles.includes(userRole)) {
    return {
      valid: false,
      reason: '当前角色无权执行此操作',
      transition: null
    };
  }
  
  // 检查子状态
  if (transition.subState && currentState.level2 !== transition.subState) {
    return {
      valid: false,
      reason: '当前子状态不允许此转换',
      transition: null
    };
  }
  
  // 检查活动状态
  if (transition.activeState && currentState.level3 !== transition.activeState) {
    return {
      valid: false,
      reason: '当前活动状态不允许此转换',
      transition: null
    };
  }
  
  return {
    valid: true,
    reason: '状态转换合法',
    transition
  };
}

/**
 * 获取当前状态下可用的事件
 * @param {Object} currentState 当前状态 {level1, level2, level3, level4}
 * @param {String} userRole 用户角色
 * @returns {Array} 可用事件列表
 */
function getAvailableEvents(currentState, userRole) {
  const events = [];
  
  // 遍历所有转换规则
  for (const [key, transition] of Object.entries(STATE_TRANSITIONS)) {
    const [state, event] = key.split('_');
    
    // 检查状态是否匹配
    if (state === currentState.level1.toString()) {
      // 检查角色权限
      if (transition.roles.includes(userRole)) {
        // 检查子状态
        if (!transition.subState || transition.subState === currentState.level2) {
          // 检查活动状态
          if (!transition.activeState || transition.activeState === currentState.level3) {
            events.push({
              code: event,
              description: transition.description
            });
          }
        }
      }
    }
  }
  
  return events;
}

module.exports = {
  STATE_TRANSITIONS,
  validateTransition,
  getAvailableEvents
}; 